const {
	search,
	searchBy,
	add
} = require('../js/mysql.js')

const router = require('koa-router')()
// 引用中间件
let jwt = require('jsonwebtoken')
let secret = require("../jwtAuth/secret")

// 用于加密算法的库
const crypto = require('crypto-js');

router.prefix('/users')

// 检查手机号是否注册
router.get('/checkUser', async function(ctx, next) {
	console.log(ctx.request.query, '-====')
	let {username} = ctx.request.query;
	console.log(20, username);
	// 查询用户名是否已存在
	let result = await searchBy('user', `username='${username}'`);
	if (result.length !== 0) {
		ctx.body = {
			code: 513,
			msg: '用户已存在',
		}
	}else {
		ctx.body = {
			code: 200,
			msg: '用户还没注册'
		}
	}
})

// 注册
router.post('/register', async function(ctx, next) {
	let {
		body
	} = ctx.request;
	let {
		username,
		password
	} = body;
	console.log(username, 19)
	// 查询用户名是否已存在
	let result = await searchBy('user', `username='${username}'`);
	// console.log(result, '-=======');
	if (result.length !== 0) {
		ctx.body = {
			code: 511,
			msg: '用户已存在',
		}
	} else {
		// 得到加密后的密码
		password = crypto.MD5(password).toString();
		let data = await add([username, password], `user(username, password) values(?,?)`);
		console.log(data)
		ctx.body = {
			code: 200,
			msg: '注册成功'
		}
	}

})

// 登录
router.post('/login', async function(ctx, next) {
	let {
		body
	} = ctx.request;
	let {
		username,
		password
	} = body;
	console.log(50, username, password);
	console.log('====================')
	// 加密密码
	password = crypto.MD5(password).toString();
	// 查询用户名密码是否正确
	let result = await searchBy('user', `username='${username}' and password='${password}'`);
	if (result.length == 0) {
		console.log(result);
		ctx.body = {
			code: 512,
			msg: '登录失败，用户名或密码错误'
		}
	} else {
		console.log(result);
		// 鉴权
		let token = jwt.sign(body, secret, {
			expiresIn: 60 * 60 * 24 * 120
		})
		console.log(81, token)
		ctx.body = {
			code: 200,
			msg: '登录成功',
			token
		}
	}
})

module.exports = router
